package com.mai4j.maiadmin.support.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class PermissionProvider implements ApplicationListener<ContextRefreshedEvent> {

    private static RequestMappingHandlerMapping requestMappingHandlerMapping;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        PermissionProvider.requestMappingHandlerMapping = applicationContext.getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class);
    }

    public static List<String> getAnnotationRequestMappingInfos(Class<? extends Annotation> annClass) {
        List<String> requestMappingInfos = new ArrayList<>();
        Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
        map.forEach((key, value) -> {
            Class<?> beanType = value.getBeanType();
            if (AnnotationUtils.findAnnotation(beanType, annClass) != null
                    || value.getMethodAnnotation(annClass) != null) {
                requestMappingInfos.add(value.toString());
            }
        });
        return requestMappingInfos;
    }
}
